package org.jeecg.modules.ws.controller;

import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;

import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.ws.dto.ExportSheetDataDto;
import org.jeecg.modules.ws.dto.UploadSheetDataDto;
import org.jeecg.modules.ws.entity.WsProject;
import org.jeecg.modules.ws.entity.WsBondInfo;
import org.jeecg.modules.ws.entity.WsBondProject;
import org.jeecg.modules.ws.entity.WsProjectSb;
import org.jeecg.modules.ws.service.IWsProjectSbService;
import org.jeecg.modules.ws.service.IWsProjectService;
import org.jeecg.modules.ws.service.IWsBondInfoService;
import org.jeecg.modules.ws.service.IWsBondProjectService;
import org.jeecg.modules.ws.util.ExcelUtil;
import org.jeecg.modules.ws.vo.ProjectListVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 债券项目信息管理
 * @Author: jeecg-boot
 * @Date: 2025-03-27
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "债券项目信息管理")
@RestController
@RequestMapping("/wsProject")
public class WsProjectController extends JeecgController<WsProject, IWsProjectService> {
    @Autowired
    private IWsProjectService wsProjectService;

    @Autowired
    private IWsBondProjectService wsBondProjectService;

    @Autowired
    private IWsBondInfoService wsBondInfoService;

    @Autowired
    private IWsProjectSbService wsProjectSbService;

    @Autowired
    private ExcelUtil excelUtil;


    /**
     * 分页列表查询
     *
     * @param wsProject
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "债券项目信息管理-分页列表查询")
    @ApiOperation(value = "债券项目信息管理-分页列表查询", notes = "债券项目信息管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(WsProject wsProject,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<WsProject> queryWrapper = QueryGenerator.initQueryWrapper(wsProject, req.getParameterMap());
        Page<WsProject> page = new Page<WsProject>(pageNo, pageSize);
        IPage<WsProject> pageList = wsProjectService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wsProject
     * @return
     */
    @AutoLog(value = "债券项目信息管理-添加")
    @ApiOperation(value = "债券项目信息管理-添加", notes = "债券项目信息管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody WsProject wsProject) {
        wsProjectService.save(wsProject);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wsProject
     * @return
     */
    @AutoLog(value = "债券项目信息管理-编辑")
    @ApiOperation(value = "债券项目信息管理-编辑", notes = "债券项目信息管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody WsProject wsProject) {
        wsProjectService.updateById(wsProject);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "债券项目信息管理-通过id删除")
    @ApiOperation(value = "债券项目信息管理-通过id删除", notes = "债券项目信息管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        wsProjectService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "债券项目信息管理-批量删除")
    @ApiOperation(value = "债券项目信息管理-批量删除", notes = "债券项目信息管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wsProjectService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "债券项目信息管理-通过id查询")
    @ApiOperation(value = "债券项目信息管理-通过id查询", notes = "债券项目信息管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        WsProject wsProject = wsProjectService.getById(id);
        return Result.OK(wsProject);
    }

    /**
     * 通过projectCode查询
     *
     * @param projectCode
     * @return
     */
    @AutoLog(value = "债券项目信息管理-通过projectCode查询")
    @ApiOperation(value = "债券项目信息管理-通过projectCode查询", notes = "债券项目信息管理-通过projectCode查询")
    @GetMapping(value = "/queryByProjectCode")
    public Result<?> queryByProjectCode(@RequestParam(name = "projectCode", required = true) String projectCode) {
        WsProject wsProject = wsProjectService.getByProjectCode(projectCode);
        return Result.OK(wsProject);
    }

    /**
     * pageList
     *
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "pageList")
    @ApiOperation(value = "pageList", notes = "pageList")
    @GetMapping(value = "/pageList")
    public Result<?> pageList(WsProject wsProject,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        QueryWrapper<WsProject> queryWrapper = QueryGenerator.initQueryWrapper(wsProject, req.getParameterMap());
        Page<WsProject> page = new Page<WsProject>(pageNo, pageSize);
        IPage<WsProject> pageList = wsProjectService.page(page, queryWrapper);
		List<WsProject> projectList = pageList.getRecords();
		List<ProjectListVo> list = new ArrayList<>();
        for (WsProject project : projectList) {
            BigDecimal totalStartAmount = BigDecimal.ZERO;
            Integer totalFxqx = 0;
			ProjectListVo vo = new ProjectListVo();
            QueryWrapper<WsBondProject> bondProjectQueryWrapper = new QueryWrapper<>();
            bondProjectQueryWrapper.eq("project_code", project.getName());
            List<WsBondProject> bondProjects = wsBondProjectService.list(bondProjectQueryWrapper);

            List<String> bondCodes = bondProjects.stream().map(WsBondProject::getBondCode).distinct().collect(Collectors.toList());
            if (!bondCodes.isEmpty()) {
                QueryWrapper<WsBondInfo> bondInfoQueryWrapper = new QueryWrapper<>();
                bondInfoQueryWrapper.in("bond_code", bondCodes);
                List<WsBondInfo> bondInfos = wsBondInfoService.list(bondInfoQueryWrapper);
				List<ProjectListVo.ProjectBondVo> bonds = new ArrayList<>();
				for (WsBondInfo bondInfo : bondInfos) {
					ProjectListVo.ProjectBondVo bondVo = new ProjectListVo.ProjectBondVo();
					bondVo.setBondId(bondInfo.getId());
					bondVo.setBondName(bondInfo.getBondName());
					bondVo.setStartAmount(bondInfo.getStartAmount());
					bondVo.setStartRate(bondInfo.getStartRate());
					bondVo.setStartTime(bondInfo.getStartTime());
					bondVo.setFxqx(bondInfo.getTimeLimit());
                    bondVo.setBondCode(bondInfo.getBondCode());
					bonds.add(bondVo);
                    totalStartAmount = totalStartAmount.add(bondVo.getStartAmount());
                    totalFxqx += bondVo.getFxqx();
				}
				vo.setBonds(bonds);
            }
			vo.setProjectId(project.getId());
			vo.setProjectName(project.getName());
			vo.setTotalAmount(project.getTotalAmount());
            vo.setTotalStartAmount(totalStartAmount);
            vo.setTotalFxqx(totalFxqx);
            vo.setProjectCode(project.getProjectCode());
			list.add(vo);
        }
		IPage<ProjectListVo> resultMap = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
		resultMap.setRecords(list);

		return Result.OK(resultMap);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param wsProject
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WsProject wsProject) {
        /*// 创建查询条件
        QueryWrapper<WsProject> queryWrapper = QueryGenerator.initQueryWrapper(wsProject, request.getParameterMap());
        List<WsProject> projectList = wsProjectService.list(queryWrapper);

        // 左连接 WsBondSb 并获取最新的一条 sqnd 记录
        List<Map<String, Object>> exportList = new ArrayList<>();
        for (WsProject project : projectList) {
            QueryWrapper<WsProjectSb> bondSbQueryWrapper = new QueryWrapper<>();
            bondSbQueryWrapper.eq("project_code", project.getProjectCode()).orderByDesc("sqnd").last("LIMIT 1");
            List<WsProjectSb> bondSbList = wsProjectSbService.list(bondSbQueryWrapper);

            Map<String, Object> projectMap = new HashMap<>();
            projectMap.putAll(JSON.parseObject(JSON.toJSONString(project)));

            if (!bondSbList.isEmpty()) {
                WsProjectSb bondSb = bondSbList.get(0); // 获取最新的一条记录
                projectMap.putAll(JSON.parseObject(JSON.toJSONString(bondSb)));
            }

            exportList.add(projectMap);
        }

        // 导出数据
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "债券项目信息管理");
        mv.addObject(NormalExcelConstants.CLASS, WsProject.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("债券项目信息管理", "导出人:" + System.getProperty("user.name")));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;*/
        QueryWrapper<WsProject> queryWrapper = QueryGenerator.initQueryWrapper(wsProject, request.getParameterMap());
        List<WsProject> list1 = wsProjectService.list(queryWrapper);
        List<WsProjectSb> list2 = new ArrayList<>();
        list1.forEach(project -> {
            String projectCode = project.getProjectCode();
            List<WsProjectSb> bondProjectList = wsProjectSbService.queryByProductCode(projectCode);
            list2.addAll(bondProjectList);
        });
        /*Map<List, Class> map = new LinkedHashMap<>();
        map.put(list1, WsBondInfo.class);
        map.put(list2, WsBondProject.class);*/
        List<ExportSheetDataDto<?>> sheetDataList = new ArrayList<>();
        sheetDataList.add(new ExportSheetDataDto<WsProject>(list1, WsProject.class,"债券项目基础信息"));
        sheetDataList.add(new ExportSheetDataDto<WsProjectSb>(list2, WsProjectSb.class,"债券项目申报信息"));
        List xls = excelUtil.packageSheet(sheetDataList);
        return excelUtil.exportXls("债券信息管理",xls);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        /*MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                // 假设导入的Excel文件中包含两个Sheet，一个用于WsProject，一个用于WsBondSb
                List<WsProject> projectList = ExcelImportUtil.importExcel(file.getInputStream(), WsProject.class, params);
                params.setSheetNum(1); // 切换到第二个Sheet
                List<WsProjectSb> bondSbList = ExcelImportUtil.importExcel(file.getInputStream(), WsProjectSb.class, params);

                for (WsProject project : projectList) {
                    LambdaUpdateWrapper<WsProject> update = Wrappers.lambdaUpdate(WsProject.class);
                    update.eq(WsProject::getProjectCode, project.getProjectCode());
                    wsProjectService.saveOrUpdate(project, update);
                }

                wsBondSbService.saveBatch(bondSbList);
                return Result.OK("文件导入成功！");
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }*/
        List<String> list1 = new ArrayList<>();
        list1.add("project_code");
        List<String> list2 = new ArrayList<>();
        list2.add("project_code");
        list2.add("sbrq");
        List<UploadSheetDataDto<?>> sheetDataList = new ArrayList<>();
        sheetDataList.add(new UploadSheetDataDto<WsProject>(WsProject.class, wsProjectService, list1));
        sheetDataList.add(new UploadSheetDataDto<WsProjectSb>(WsProjectSb.class, wsProjectSbService, list2));
        return excelUtil.importExcel(request, response, sheetDataList);
    }

}
